<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Dao;

use App\Kernel\Traits\DaoTrait;
use App\Model\UserFav;

/**
 * 用户收藏 Dao
 *
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Dao
 */
class UserFavDao extends Dao
{
    use DaoTrait;

    /**
     * @inheritDoc
     */
    public function model(): string
    {
        return UserFav::class;
    }

    /**
     * 根据条件获取收藏个数
     *
     * @param array $map
     * @return int
     */
    public function count(array $map = [])
    {
        return UserFav::query()->where(function($query) use ($map) { return queryWhere($query, $map); })->count();
    }

    /**
     * 获取商品收藏状态
     *
     * @param int $user_id
     * @param int $goods_id
     * @return bool
     */
    public function getGoodsFavStatus(int $user_id, int $goods_id)
    {
        return self::makeModel()->where('user_id', $user_id)->where('goods_id', $goods_id)->exists();
    }

    /**
     * 根据条件判获取收藏
     *
     * @param array $map
     * @return mixed
     */
    public function first(array $map = [])
    {
        return UserFav::query()->where(function($query) use ($map) { return queryWhere($query, $map); })->first();
    }

    /**
     * 列表
     *
     * @param array $map
     * @return mixed
     */
    public function get(array $map = [])
    {
        return UserFav::query()
            ->with('goods:id,title,buy_type,picture,price,integral')
            ->withCount('goodsFav')
            ->where(function($query) use ($map) {
                return queryWhere($query, $map);
            })
            ->orderByDesc('fav_time')
            ->orderBy('id')
            ->select('id', 'goods_id', 'status', 'fav_time')
            ->paginate(10);
    }

    /**
     * 创建收藏
     *
     * @param array $data
     * @return mixed
     */
    public function create(array $data)
    {
        return UserFav::query()->create($data);
    }

    /**
     * 删除
     *
     * @param array $map
     * @return int
     */
    public function delete(array $map = [])
    {
        return UserFav::query()->where(function($query) use ($map) {
            return queryWhere($query, $map);
        })->delete();
    }
}